package cn.asterly.cicada.web.shiro;

import cn.asterly.cicada.model.User;
import cn.asterly.cicada.service.impl.UserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * @ Author     ：likun
 * @ Date       ：Created in 20:15 2019-02-23
 * @ Description：
 * @Version: $
 */
public class MyRealm2 extends AuthorizingRealm {

    @Autowired
    private UserServiceImpl userService;

    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //权限验证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限验证");
        String sql="select name from role where id in(SELECT role_id FROM " +
                " users_roles where user_id=(SELECT id from user where email=?))";
        String username=(String) principalCollection.getPrimaryPrincipal();

        List<String> roles=jdbcTemplate.queryForList(sql,String.class,username);
        //封装到权限信息里
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRoles(roles);
        return null;
    }

    //登录时验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("登录验证");
        String username= (String) authenticationToken.getPrincipal();
        User user = userService.loginByEmail(username);
//        String password="e10adc3949ba59abbe56e057f20f883e";
        SimpleAuthenticationInfo info=null;
        if(user!=null){
            info= new SimpleAuthenticationInfo(username,user.getPassword(),getName());
        }
        return info;
    }

}
